<template>
	<el-card style="width: 70%; margin-left: 15%; height: 89vh;" >
		<el-form ref="formObj" :model="centerform" :rules="rules" label-width="100" style="padding-right: 70px; " >
			<el-form-item label="头像" prop="file">
				<div style="width: 150px; height: 150px; overflow: hidden; ">
					<el-upload 
				list-type="picture-card" 
				:auto-upload="false"
				action="#"
				:limit="1"
				:on-change="uploadFile"
				:on-remove="removeFile"
				v-model:file-list="fileList"
				:disabled="!fix">
				<el-icon><PictureFilled /></el-icon>
				</el-upload>
				</div>
			</el-form-item>
			<el-form-item label="姓名" prop="name">
				<el-input v-model="centerform.name" autocomplete="off" :readonly="!fix"></el-input>
			</el-form-item>
			<el-form-item label="性别" prop="sex">
				<el-radio-group :disabled="!fix" v-model="centerform.sex">
					<el-radio :value="1">男</el-radio>
					<el-radio :value="0">女</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="身份证号" prop="idcard">
				<sensitiveInfo v-if="!fix" v-model="centerform.idcard" :maskLength="4"></sensitiveInfo>
				<el-input v-if="fix" v-model="centerform.idcard"></el-input>
			</el-form-item>
			<el-form-item label="手机号" prop="phone">
				<sensitiveInfo v-if="!fix" v-model="centerform.phone" :maskLength="3"></sensitiveInfo>
				<el-input v-if="fix" v-model="centerform.phone"></el-input>
			</el-form-item>
			<el-form-item label="电子信箱" prop="email">
				<el-input :readonly="!fix" v-model="centerform.email" autocomplete="off"></el-input>
			</el-form-item>
			<el-link style="margin-left: 18px; margin-bottom: 10px;" type="primary" :underline="false">请选择您要查看的辖区:</el-link>
				<div class="form-row">
				  <el-form-item class="form-item" label="省" prop="province">
					<el-select :disabled="!fix || roleId===0 || (hasPro && (roleId!=3))" v-model="centerform.province" @change="onProvinceChange">
					  <el-option v-for="province in provinces" :key="province.code" :label="province.name" :value="province.name"></el-option>
					</el-select>
				  </el-form-item>
				  <el-form-item class="form-item" label="市" prop="city">
					<el-select :disabled="!fix || roleId===0 || hasCit" v-model="centerform.city" @change="onCityChange">
					  <el-option v-for="city in cities" :key="city.code" :label="city.name" :value="city.name"></el-option>
					</el-select>
				  </el-form-item>
				</div>
				<div class="form-row">
				  <el-form-item class="form-item" label="县(区)" prop="county">
					<el-select :disabled="!fix || roleId===0 || hasCou" v-model="centerform.county" @change="onCountyChange">
					  <el-option v-for="county in counties" :key="county.code" :label="county.name" :value="county.name"></el-option>
					</el-select>
				  </el-form-item>
				  <el-form-item class="form-item" label="乡(镇)" prop="township">
					<el-select :disabled="!fix || roleId===0 || hasTow" v-model="centerform.township" @change="onTownshipChange">
					  <el-option v-for="township in townships" :key="township.code" :label="township.name" :value="township.name"></el-option>
					</el-select>
				  </el-form-item>
				</div>
		</el-form>
		<div class="wrapper">
			<div v-if="!fix">
				<el-button type="warning" plain style="margin-top: 50px; margin-right: 50px;" :icon="Fix" @click="fixInfo">修改信息</el-button>
				<el-button type="danger" style="margin-top: 50px; margin-left: 50px;" :icon="FixPassword" @click="fixPassword">修改密码</el-button>
			</div>
			<div v-if="fix">
				<el-button type="primary" plain style="margin-top: 50px; margin-right: 50px;" :icon="Leave" @click="leave">退出修改</el-button>
				<el-button type="success" plain style="margin-top: 50px; margin-left: 50px;" :icon="Save" @click="save">保存信息</el-button>
			</div>
		</div>
		<el-dialog
		v-model="confimDialog.show"
		title="修改密码"
		width="650px"
		:close-on-click-modal="false"
		>
		<Confim v-model:show="confimDialog.show"/>
		</el-dialog>
	</el-card>
</template>

<script setup>
import areaData from '@/area/pcas-code.json'
import axios from 'axios'
import { PictureFilled } from '@element-plus/icons-vue'
import { get,post } from '@/axios'
import { ref,onMounted ,watch,reactive } from 'vue'
import { getPath } from '@/util'
import Save from '@/components/icons/save' 
import { userIdStore,userAreaStore } from '@/stores'
import url from './util'
import sensitiveInfo from '@/components/Sensitive'
import Fix from '@/components/icons/fix'
import Leave from '@/components/icons/leave'
import Confim from './password'
import FixPassword from '@/components/icons/fixPassword'

const areaStore = userAreaStore()
const idStore = userIdStore()
const fileList = reactive([])
const fix = ref(false)
const centerform =reactive({
	id:null,
	name: '',
	sex: null,
	idcard:'',
	phone:'',
	email: '',
	province: '',
	city: '',
	county: '',
	township: '',
	areaId:null
});
const roleId = ref(0)
const hasPro = ref(true)
const hasCit = ref(false)
const hasCou= ref(false)
const hasTow = ref(false)

const confimDialog = reactive({
	show: false
})
const rules = reactive({
	name: [
		{ required: true, message: '请输入管理员姓名', trigger: 'blur' }
	],
	sex: [
		{ required: true, message: '请选择管理员性别', trigger: 'blur' }
	],
	phone: [
		{ required: true, message: '请输入手机号码', trigger: 'blur' },
		{ pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/, message: '请输入正确的中国手机号', trigger: 'blur' },
		{ validator: check, message: '该手机号已经被使用', trigger: 'blur' }
	],
	email: [
		{ required: true, message: '请输入电子信箱', trigger: 'blur' },
		{ type: 'email', message: '请输入正确的电子信箱', trigger: 'blur' },
		{ validator: check, message: '该电子信箱已经被使用', trigger: 'blur' }
	],
	idcard: [
		{ required: true, message: '请输入身份证号', trigger: 'blur' },
		{ pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' },
		{ validator: check, message: '该身份证号已经被使用', trigger: 'blur' }
	],
	province: [
		{ required: hasPro, message: '请选择辖区省份', trigger: 'blur' }
	],
	city: [
		{ required: hasCit, message: '请选择辖区城市', trigger: 'blur' }
	],
	county: [
		{ required: hasCou, message: '请选择辖区县（区）', trigger: 'blur' }
	],
	township: [
		{ required: hasTow, message: '请输入辖区乡（镇）', trigger: 'blur' }
	],
})
const formObj = ref()

const provinces = ref([]);
const cities = ref([]);
const counties = ref([]);
const townships = ref([]);

function check(rule,value,callback){
	get(url.check, { id: idStore.userId, value, field: rule.field }, content => {
			if (content) {
				callback()
			} else {
				callback(new Error())
			}
		})
}
function save(){
	formObj.value.validate(valid=>{
		if(valid){
			post(url.update,centerform,content => {
				fix.value = false
			})
		}
	})
}
function uploadFile(file){
	centerform.file=file.raw
}
function removeFile(){
	centerform.file=null
}
function getAdmin(){
	get('/admin/center',{ id:idStore.userId }, content=>{
		console.dir(content)
		for(const key in centerform){
			if (Object.prototype.hasOwnProperty.call(content.admin, key)) {
				centerform[key]=content.admin[key]
			}
		}
		fileList.push({ url: getPath(content.admin.icon) })
		roleId.value = content.roleId
		if( content.roleId === 0 ) {
			hasPro.value = false
		}
		if(content.roleId === 5) {
			hasCit.value = true
		}
		if(content.roleId === 7) {
			hasCit.value = true
			hasCou.value = true
		}
		if(content.roleId === 9 || content.roleId === 8) {
			hasCit.value = true
			hasCou.value = true
			hasTow.value = true
		}
		if (centerform.province) {
		  // 初始化市级数据
		  const selectedProvince = provinces.value.find(province => province.name === centerform.province);
		  if (selectedProvince) {
		    cities.value = selectedProvince.cities.map(city => ({
		      name: city.name,
		      code: city.code,
		      counties: city.children || [],
		    }));
		    areaStore.setUserArea(selectedProvince.code);
		    centerform.areaId = selectedProvince.code;
		  }
		
		  if (centerform.city) {
		    // 初始化县级数据
		    const selectedCity = cities.value.find(city => city.name === centerform.city);
		    if (selectedCity) {
		      counties.value = selectedCity.counties.map(county => ({
		        name: county.name,
		        code: county.code,
		        townships: county.children || [],
		      }));
		      areaStore.setUserArea(selectedCity.code);
		      centerform.areaId = selectedCity.code;
		    }
		
		    if (centerform.county) {
		      // 初始化乡级数据
		      const selectedCounty = counties.value.find(county => county.name === centerform.county);
		      if (selectedCounty) {
		        townships.value = selectedCounty.townships.map(township => ({
		          name: township.name,
		          code: township.code,
		        }));
		        areaStore.setUserArea(selectedCounty.code);
		        centerform.areaId = selectedCounty.code;
		      }
		    }
		  }
		}
	})
}
function fixInfo() {
	fix.value = true
}
function leave() {
	fix.value = false
}
function fixPassword() {
	confimDialog.show = true
}
onMounted(() => {
  provinces.value = areaData.map(province => ({
    name: province.name,
    code: province.code,
    cities: province.children || [],
  }));

});

// 选择省份后加载市
const onProvinceChange = (value) => {
  centerform.province = value;
  centerform.city = '';
  centerform.county = '';
  centerform.township = '';

  const selectedProvince = provinces.value.find(province => province.name === value);

  if (selectedProvince) {
    cities.value = selectedProvince.cities.map(city => ({
      name: city.name,
      code: city.code,
      counties: city.children || [],
    }));
  } else {
    cities.value = [];
  }

  counties.value = [];
  townships.value = [];
  areaStore.setUserArea(selectedProvince ? selectedProvince.code : null);
  centerform.areaId = selectedProvince ? selectedProvince.code : null;
};

// 选择市后加载县
const onCityChange = (value) => {
  centerform.city = value;
  centerform.county = '';
  centerform.township = '';

  const selectedCity = cities.value.find(city => city.name === value);

  if (selectedCity) {
    counties.value = selectedCity.counties.map(county => ({
      name: county.name,
      code: county.code,
      townships: county.children || [],
    }));
  } else {
    counties.value = [];
  }

  townships.value = [];
  areaStore.setUserArea(selectedCity ? selectedCity.code : null);
  centerform.areaId = selectedCity ? selectedCity.code : null;
};

// 选择县后加载乡
const onCountyChange = (value) => {
  centerform.county = value;
  centerform.township = '';

  const selectedCounty = counties.value.find(county => county.name === value);

  if (selectedCounty) {
    townships.value = selectedCounty.townships.map(township => ({
      name: township.name,
      code: township.code,
    }));
  } else {
    townships.value = [];
  }
  areaStore.setUserArea(selectedCounty ? selectedCounty.code : null);
  centerform.areaId = selectedCounty ? selectedCounty.code : null;
};

const onTownshipChange = (value) => {
  centerform.township = value;
  const townshipData = townships.value.find(township => township.name === value);
  areaStore.setUserArea(townshipData ? townshipData.code : null);
  centerform.areaId = townshipData ? townshipData.code : null;
};


getAdmin()
</script>

<style scoped lang="scss">
$MyBorder: 1px solid #cccccc;
.form-row {
  display: flex;
  gap: 20px; 
  margin-top: 10px;
  .form-item {
    flex: 1; 
  }
}
.wrapper {
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>